'''
需求：写一个接口，传递以下参数，书本的名称，描述，价格，打折。
接口返回返回最后的价格
'''
import uvicorn
from fastapi import FastAPI, Body
from typing import Optional
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    desc: Optional[str] = None
    price: float
    tax: Optional[float] = None


class User(BaseModel):
    username: str
    year: str


# @app.post('/items')
# def update_item(item: Optional[Item], user: User):
#     result = {}
#     if item.tax is not None:
#         total = item.price * item.tax
#         result["price"] = total
#         result["name"] = item.name
#         result['user'] = user
#         return result
#     result["price"] = item.price
#     result["name"] = item.name
#     result['user'] = user
#     return result


'''
多个请求体需要发送时， item 参数将接收指定的内容，user 参数也是如此。
{ 
    "item":{
    "name":"lxq",
    "desc":"danmin",
    "price":231.21,
    "tax":0.9
    },
 "user": {
    "username":"wudi",
    "year":"2021"
    }
}
'''


# 如果想在请求体中再加一个键，如何实现呢  ==》 Body
@app.post('/items')
async def update_item(item: Optional[Item],user:User,sell:str=Body(...)):
    result={}
    if  item.tax is not None:
        total=item.price*item.tax
        result['price'] = total
        result['name']=item.name
        result['user']=user
        result['sell']=sell
        return result
    result['price'] = item.price
    result['name'] = item.name
    result['user']=user
    result['sell'] = sell
    return result

if __name__ == '__main__':
    uvicorn.run(app="main:app", host="127.0.0.1", port=8000, reload=True, debug=True)
